package com.example.server.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.server.web.domain.Role;
import com.example.server.web.domain.UserRole;
import com.example.server.web.mapper.UserRoleMapper;
import com.example.server.web.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 作者
 * @since 2023-04-04
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public List<Role> getRolesByUserId(Long userId) {
        return userRoleMapper.getRolesByUserId(userId);
    }

    @Override
    public Integer judgeRoleByUsername(String username, Long roleId) {
        return userRoleMapper.judgeRoleByUsername(username,roleId);
    }

    @Override
    public Integer insertUserRoles(Long userId, List<Long> roleIdList) {
        Integer count = 0;
        UserRole userRole = new UserRole();
        userRole.setUserId(userId);
        for (Long role: roleIdList) {
            userRole.setRoleId(role);
            userRoleMapper.insert(userRole);
            count ++;
        }
        return count;
    }

    @Override
    public Integer updateUserRoles(Long userId, List<Long> roleIdList) {
        deleteUserRoles(userId);

        return insertUserRoles(userId,roleIdList);
    }

    @Override
    public Integer deleteUserRoles(Long userId) {
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(userId != null,UserRole::getUserId,userId);

        return userRoleMapper.delete(queryWrapper);
    }
}
